package com.elite.groovy.callback

import com.elite.groovy.kh.KHDBConfig
import com.elite.groovy.kh.KHUtil
import com.elite.groovy.util.EliteBean
import com.elite.groovy.util.Util
import net.sf.json.JSONObject
import org.apache.commons.logging.Log
import org.apache.commons.logging.LogFactory
import org.springframework.jdbc.core.JdbcTemplate

import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse

/**
 *
 * @Title: apiSSOLoginControl
 *
 */

public class apiSSOLoginControl implements ServiceBackInvoke {
    private static final Log log = LogFactory.getLog(apiSSOLoginControl.class);
    private static String userInfoURL = "";

    public String doCallBack(EliteBean eliteBean, HttpServletRequest request, HttpServletResponse response) {

        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=UTF-8");
        long startTime = System.currentTimeMillis();

        String callBody = "";
        JSONObject outData = JSONObject.fromObject("{\"code\":1,\"message\":\"操作成功\"}");
        String getMethod = request.getMethod();
        log.debug("apiMiniPControl getMethod:" + getMethod);

        // 获取所有Header
        Map<String, String> mapHeader = new HashMap<String, String>();
        Enumeration headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String key = (String) headerNames.nextElement();
            String value = request.getHeader(key);
            log.debug("apiMiniPControl Header-" + key + ":" + value);

            mapHeader.put(key, value);
        }

        // 获取所有参数名
        Map<String, String> mapParams = new HashMap<String, String>();
        Enumeration ep = request.getParameterNames();
        while (ep.hasMoreElements()) {
            String key = (String) ep.nextElement();
            String value = request.getParameter(key);
            log.debug("apiMiniPControl Parameter-" + key + ":" + value);
            mapParams.put(key, value);

        }
        log.debug("***原始GET请求参数:" + mapParams.toString());

        // 请求参数信息
        if (getMethod.equals("POST")) {
            InputStreamReader reader = new InputStreamReader(request.getInputStream(), "UTF-8");
            BufferedReader iny = new BufferedReader(reader);
            String line;
            while ((line = iny.readLine()) != null) {
                callBody += line;
            }
            log.debug("***原始POST请求参数:" + callBody);
        }

        if (!getMethod.equals("POST")) {
            outData.put("code", -1);
            outData.put("message", "HTTP请求调用类型错误，接口调用失败：" + getMethod);
            log.error(outData);
            return outData.toString();
        }

        // 获取数据源List<Map<String, Object>>
        JdbcTemplate jt = new JdbcTemplate(eliteBean.getDataSource());

        try {
            // 获取嵌入传递的参数(https://ccctest.davco.cn/ngs/login?code=DJTRI7ydPNK2SMIBnj2AljfVIlJ8FUXQe8k6LodJe9A&state=ecm&appid=ww7d71901792416fd0)
            String state = mapParams.get("state");
            log.debug("获取调用参数 state:" + state);

            if (state == "wxq") {
                outData = doQWLogin(eliteBean, jt, mapParams, callBody);
            } else {
                outData.put("code", -3);
                outData.put("message", "不支持的登录类型(" + state + ")!");
            }

        } catch (Exception e) {
            outData.put("code", -2);
            outData.put("message", "HTTP请求调用错误(" + apiSSOLoginControl + "),请稍后再试!");
            log.error(outData, e);
            return outData.toString();

        }
        log.debug("单点登录apiSSOLoginControl校验返回:" + outData.toString());
        return outData.toString();

    }

    // 企微扫码登录
    public static JSONObject doQWLogin(EliteBean eliteBean, JdbcTemplate jt, Map<String, String> mapParams, String callBody) throws Exception {

        JSONObject resJson = JSONObject.fromObject("{\"code\":1,\"message\":\"操作成功\"}");

        // 获取嵌入传递的参数(https://ccctest.davco.cn/ngs/login?code=DJTRI7ydPNK2SMIBnj2AljfVIlJ8FUXQe8k6LodJe9A&state=ecm&appid=ww7d71901792416fd0)
        String code = mapParams.get("code");
        log.debug("企微扫码登录- 获取调用参数 code:" + code);

        if (KHUtil.isNull(code)) {
            resJson.put("code", -1);
            resJson.put("message", "获取code信息错误，接口调用 code：" + code);
            return resJson;
        }

        // 获取企微Token
        JSONObject apiTokenJson = JSONObject.fromObject(Util.doHttpGet(KHDBConfig.getAPIURL(eliteBean, "SYS-InnerDomain") + "groovy/GeneralService/apiGetToken?appid=WXG_DAVCO", "UTF-8", 12000, 0));
        log.debug("企微扫码登录- 获取企微Token 调用返回：" + apiTokenJson.toString());

        // 获取调用URL
        String callURL = "https://qyapi.weixin.qq.com/cgi-bin/auth/getuserinfo?access_token=" + apiTokenJson.getJSONObject("value").getString("access_token") + "&code=" + code;
        log.debug("企微扫码登录- 获取调用URL 调用URL：" + callURL);

        // 通过Token+code获取企微当前扫码人信息
        JSONObject userInfoJSON = JSONObject.fromObject(Util.doHttpGet(callURL, "UTF-8", 5000, 0));
        log.debug("企微扫码登录- 通过Token+code获取企微当前扫码人信息 返回：" + userInfoJSON.toString());

        if (userInfoJSON.containsKey("userid")) {
            String userid = userInfoJSON.getString("userid");

            // 检查当前登录用户在系统中是否有效(人&组&关系)
            String checkSQL = "Select Staff_Id, Staffname, Loginname, Workstatus From Staff Where userid = ?";
            List<Map<String, Object>> checkSQLResult = jt.queryForList(checkSQL, userid);
            log.debug("企微扫码登录- 检查当前登录用户在系统中是否有效-结果:" + checkSQLResult.toString());

            // 如果人员信息不存在-新建
            if (checkSQLResult.size() <= 0) {

                resJson.put("code", -4);
                resJson.put("message", "您的身份信息未查询到请使用账号密码登录,并将该问题反馈系统管理员 code:" + code);

            } else {
                try {
                    // 扫码登录成功后将密码修改时间和错误次数重置
                    jt.update("Update Staff Set Pwdmodify = Now(), Wrongpwdcount = 0 Where Staff_Id = ?", checkSQLResult.get(0).get("Staff_Id"));
                } catch (Exception e) {
                    log.warn("扫码登录成功后将密码修改时间和错误次数重置-失败" + e.getMessage());

                }
                String loginName = checkSQLResult.get(0).get("Loginname");
                resJson.put("loginName", loginName);
                resJson.put("message", "人员信息已存在-直接登录[" + loginName + "]");

            }

        } else {
            resJson.put("code", -2);
            resJson.put("message", "获取Token用户信息接口返回错误，接口调用：" + userInfoJSON.toString());

        }

        return resJson;

    }

}